/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package sys.donto.telas;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import sys.donto.paciente.Paciente;
import sys.donto.paciente.PacienteDAO;
import sys.donto.paciente.PacienteTableModel;
import sys.donto.prontuario.Prontuario;
import sys.donto.prontuario.ProntuarioDAO;
import sys.donto.prontuario.ProntuarioTableModel;
import sys.donto.servico.Servico;
import sys.donto.servico.ServicoDAO;
import sys.donto.servico.ServicoTableModel;
import sys.donto.servico.ServicoTableModel2;
import sys.donto.util.Util;

/**
 *
 * @author JOABB
 */
public class telaProntuarioPaciente extends javax.swing.JDialog {
     Prontuario prontuario;
     private List<Servico> servicos = new ArrayList<Servico>();
     
    Paciente pacientePesquisado = new Paciente();
    
    /**
     * Creates new form telaProntuarioPaciente
     */
    
    public telaProntuarioPaciente() {
        initComponents();
        setModal(true);
       setLocationRelativeTo(null);
       limpaCampos();
       setTitle("sysDONTO - Prontuário paciente");
       limpaCampos();
    }
  
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel5 = new javax.swing.JPanel();
        btPesquisarPaciente1 = new javax.swing.JButton();
        tfPaciente = new javax.swing.JTextField();
        jlServico = new javax.swing.JLabel();
        btPesquisarServico1 = new javax.swing.JButton();
        btExcluirServico = new javax.swing.JButton();
        jlData = new javax.swing.JLabel();
        jlPaciente1 = new javax.swing.JLabel();
        tfData = new javax.swing.JFormattedTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        tbServicos = new javax.swing.JTable();
        jlData1 = new javax.swing.JLabel();
        tfIdProntuario = new javax.swing.JTextField();
        btPesquisar = new javax.swing.JButton();
        btSalvar = new javax.swing.JButton();
        btNovo = new javax.swing.JButton();
        btSair1 = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        jLFundo = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        jPanel5.setBackground(new java.awt.Color(255, 255, 255));
        jPanel5.setLayout(null);

        btPesquisarPaciente1.setBackground(new java.awt.Color(0, 153, 153));
        btPesquisarPaciente1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/sys/donto/imagens/Search 16.png"))); // NOI18N
        btPesquisarPaciente1.setToolTipText("Pesquisar Paciente");
        btPesquisarPaciente1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btPesquisarPaciente1ActionPerformed(evt);
            }
        });
        jPanel5.add(btPesquisarPaciente1);
        btPesquisarPaciente1.setBounds(640, 160, 37, 25);

        tfPaciente.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
        tfPaciente.setEnabled(false);
        tfPaciente.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                tfPacienteActionPerformed(evt);
            }
        });
        tfPaciente.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                tfPacienteFocusLost(evt);
            }
        });
        jPanel5.add(tfPaciente);
        tfPaciente.setBounds(130, 160, 500, 20);

        jlServico.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jlServico.setText("SERVIÇO:");
        jPanel5.add(jlServico);
        jlServico.setBounds(60, 200, 70, 15);

        btPesquisarServico1.setBackground(new java.awt.Color(0, 153, 153));
        btPesquisarServico1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/sys/donto/imagens/Search 16.png"))); // NOI18N
        btPesquisarServico1.setToolTipText("Pesquisar Serviço");
        btPesquisarServico1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btPesquisarServico1ActionPerformed(evt);
            }
        });
        jPanel5.add(btPesquisarServico1);
        btPesquisarServico1.setBounds(640, 190, 37, 25);

        btExcluirServico.setBackground(new java.awt.Color(0, 153, 153));
        btExcluirServico.setForeground(new java.awt.Color(0, 153, 153));
        btExcluirServico.setIcon(new javax.swing.ImageIcon(getClass().getResource("/sys/donto/imagens/trash16x16.png"))); // NOI18N
        btExcluirServico.setToolTipText("Novo Serviço");
        btExcluirServico.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btExcluirServicoActionPerformed(evt);
            }
        });
        jPanel5.add(btExcluirServico);
        btExcluirServico.setBounds(640, 220, 37, 25);

        jlData.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jlData.setText("Abertura de Prontuário:");
        jPanel5.add(jlData);
        jlData.setBounds(240, 130, 150, 20);

        jlPaciente1.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jlPaciente1.setText("PACIENTE:");
        jPanel5.add(jlPaciente1);
        jlPaciente1.setBounds(60, 160, 70, 15);

        tfData.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
        try {
            tfData.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##/##/####")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        tfData.setEnabled(false);
        jPanel5.add(tfData);
        tfData.setBounds(400, 130, 110, 20);

        tbServicos.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane1.setViewportView(tbServicos);

        jPanel5.add(jScrollPane1);
        jScrollPane1.setBounds(130, 190, 500, 140);

        jlData1.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jlData1.setText("PRONTUARIO Nº:");
        jPanel5.add(jlData1);
        jlData1.setBounds(20, 130, 120, 20);

        tfIdProntuario.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
        tfIdProntuario.setEnabled(false);
        tfIdProntuario.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                tfIdProntuarioActionPerformed(evt);
            }
        });
        jPanel5.add(tfIdProntuario);
        tfIdProntuario.setBounds(130, 130, 80, 20);

        btPesquisar.setBackground(new java.awt.Color(0, 153, 153));
        btPesquisar.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        btPesquisar.setForeground(new java.awt.Color(255, 255, 255));
        btPesquisar.setMnemonic('P');
        btPesquisar.setText("PESQUISAR");
        btPesquisar.setToolTipText("Pesquisar");
        btPesquisar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btPesquisarActionPerformed(evt);
            }
        });
        jPanel5.add(btPesquisar);
        btPesquisar.setBounds(460, 370, 103, 30);

        btSalvar.setBackground(new java.awt.Color(0, 153, 153));
        btSalvar.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        btSalvar.setForeground(new java.awt.Color(255, 255, 255));
        btSalvar.setMnemonic('S');
        btSalvar.setText("SALVAR");
        btSalvar.setToolTipText("Salvar");
        btSalvar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btSalvarActionPerformed(evt);
            }
        });
        jPanel5.add(btSalvar);
        btSalvar.setBounds(370, 370, 83, 30);

        btNovo.setBackground(new java.awt.Color(0, 153, 153));
        btNovo.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        btNovo.setForeground(new java.awt.Color(255, 255, 255));
        btNovo.setMnemonic('N');
        btNovo.setText("NOVO");
        btNovo.setToolTipText("Novo");
        btNovo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btNovoActionPerformed(evt);
            }
        });
        jPanel5.add(btNovo);
        btNovo.setBounds(300, 370, 67, 30);

        btSair1.setBackground(new java.awt.Color(0, 153, 153));
        btSair1.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        btSair1.setForeground(new java.awt.Color(255, 255, 255));
        btSair1.setMnemonic('S');
        btSair1.setText("SAIR");
        btSair1.setToolTipText("Sair");
        btSair1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btSair1ActionPerformed(evt);
            }
        });
        jPanel5.add(btSair1);
        btSair1.setBounds(570, 370, 63, 30);

        jLabel3.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
        jLabel3.setForeground(new java.awt.Color(255, 255, 255));
        jLabel3.setText("PRONTUÁRIO");
        jLabel3.setFocusable(false);
        jPanel5.add(jLabel3);
        jLabel3.setBounds(210, 40, 360, 40);

        jLFundo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/sys/donto/imagens/telaM.jpg"))); // NOI18N
        jPanel5.add(jLFundo);
        jLFundo.setBounds(0, 0, 740, 440);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, 740, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, 441, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, 0))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

   private void limpaCampos(){
        tfPaciente.setText("");
        servicos.clear();
        preencheTabelaDisciplinas();
        prontuario = new Prontuario();
        tfIdProntuario.setText("");
        
    }
    
    private void preencheTabelaDisciplinas() {
        ServicoTableModel2 stm = new ServicoTableModel2(servicos);
        tbServicos.setModel(stm);
    }
    
    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
        Date datasistema = new Date(); //a data do sistema é no tipo Date
        SimpleDateFormat formato = new SimpleDateFormat ("dd/MM/yyyy"); //instanciei um formato de data do sistema e alterei para uma label
        tfData.setText(formato.format(datasistema));
    }//GEN-LAST:event_formWindowOpened

    private void btPesquisarPaciente1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btPesquisarPaciente1ActionPerformed
        PacienteDAO dao = new PacienteDAO();
        List<Paciente> lista = dao.listar();
        PacienteTableModel ptm = new PacienteTableModel(lista);
        Object o = telaPesquisa.exibeTela(ptm, "paciente");
        Paciente p;
            
        if (o != null) {
            p = dao.pesquisaId(Integer.valueOf(String.valueOf(o)));
            prontuario.setPaciente(p);
            tfPaciente.setText(p.getNome());
        }         // TODO add your handling code here:
    }//GEN-LAST:event_btPesquisarPaciente1ActionPerformed

    private void tfPacienteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tfPacienteActionPerformed
            // TODO add your handling code here:
    }//GEN-LAST:event_tfPacienteActionPerformed
    
    private void btPesquisarServico1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btPesquisarServico1ActionPerformed
        ServicoDAO dao = new ServicoDAO();
        List<Servico> lista = dao.listar();
        ServicoTableModel stm = new ServicoTableModel(lista);
        Object o = telaPesquisa.exibeTela(stm, "servico");
        Servico s;
            if (o != null) {
            s = dao.pesquisaId(Integer.valueOf(String.valueOf(o)));
                    servicos.add(s);
                    preencheTabelaDisciplinas();
            
            }
    }//GEN-LAST:event_btPesquisarServico1ActionPerformed

    private void btExcluirServicoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btExcluirServicoActionPerformed
        servicos.remove(tbServicos.getSelectedRow());
         preencheTabelaDisciplinas();
    }//GEN-LAST:event_btExcluirServicoActionPerformed

    private void btNovoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btNovoActionPerformed
        limpaCampos();
//        dispose();
//        telaProntuarioPaciente tp = new telaProntuarioPaciente();
//        tp.setVisible(true);
    }//GEN-LAST:event_btNovoActionPerformed

    private void btSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btSalvarActionPerformed
            
       if (Util.chkVazio(tfPaciente.getText())){
 
            //Condição para verificação se campos estão vzios.
         //METODO NECESSÁRIO PARA SALVAR A DATA NO BANCO DE DADOS
        try {
            if (!tfData.getText().replaceAll("/", "").isEmpty()) {
                DateFormat fmt = new SimpleDateFormat("dd/MM/yyyy");
                java.util.Date data1;
                data1 = new java.util.Date(fmt.parse(tfData.getText()).getTime());
                prontuario.setDataAtualizacao(data1);
            }
        } catch (ParseException ex) {
            Logger.getLogger(telaConsulta.class.getName()).log(Level.SEVERE, null, ex);

        }
        
        prontuario.setServicos(servicos);
        ProntuarioDAO dao = new ProntuarioDAO();
        dao.salvar(prontuario);// chama o metodo salvar da classe cidade.
        limpaCampos();

        JOptionPane.showMessageDialog(rootPane, "Prontuario Salvo com sucesso!");
        }

    }//GEN-LAST:event_btSalvarActionPerformed

    private void btPesquisarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btPesquisarActionPerformed
        limpaCampos();
        ProntuarioDAO dao = new ProntuarioDAO();
        List <Prontuario> prontuarios = (!tfPaciente.getText().isEmpty() ? dao.pesquisaDescricao(tfPaciente.getText())
            : dao.listar()); 

        ProntuarioTableModel ptm = new ProntuarioTableModel(prontuarios);

        Object o = telaPesquisa.exibeTela(ptm, "Prontuario");

        if (o != null){
            prontuario = new Prontuario();
            prontuario = dao.pesquisaId(Integer.valueOf(String.valueOf(o)));

            
            tfIdProntuario.setText(Integer.toString(prontuario.getId()));
            
            SimpleDateFormat sf = new SimpleDateFormat("dd/MM/yyyy");
            tfData.setText(sf.format(prontuario.getDataAtualizacao()));
            
            servicos=prontuario.getServicos();
            preencheTabelaDisciplinas();
            tfPaciente.setText(prontuario.getPaciente().getNome());
        
        }
    }//GEN-LAST:event_btPesquisarActionPerformed

    private void btSair1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btSair1ActionPerformed
        dispose();
    }//GEN-LAST:event_btSair1ActionPerformed

    private void tfIdProntuarioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tfIdProntuarioActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_tfIdProntuarioActionPerformed

    private void tfPacienteFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_tfPacienteFocusLost
        PacienteDAO dao = new PacienteDAO();
            pacientePesquisado = dao.pesquisaNome(tfPaciente.getText());
            if (pacientePesquisado.toString() == prontuario.getPaciente().getNome()) {
                JOptionPane.showMessageDialog(rootPane, "Prontuário de Paciente já cadastrado!");
            }
    }//GEN-LAST:event_tfPacienteFocusLost

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(telaProntuarioPaciente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(telaProntuarioPaciente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(telaProntuarioPaciente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(telaProntuarioPaciente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new telaProntuarioPaciente().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btExcluirServico;
    private javax.swing.JButton btNovo;
    private javax.swing.JButton btPesquisar;
    private javax.swing.JButton btPesquisarPaciente1;
    private javax.swing.JButton btPesquisarServico1;
    private javax.swing.JButton btSair1;
    private javax.swing.JButton btSalvar;
    private javax.swing.JLabel jLFundo;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel jlData;
    private javax.swing.JLabel jlData1;
    private javax.swing.JLabel jlPaciente1;
    private javax.swing.JLabel jlServico;
    private javax.swing.JTable tbServicos;
    private javax.swing.JFormattedTextField tfData;
    private javax.swing.JTextField tfIdProntuario;
    private javax.swing.JTextField tfPaciente;
    // End of variables declaration//GEN-END:variables
}
